package com.zrx.springboot.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zrx.springboot.entity.Address;
import com.zrx.springboot.entity.Admin;
import com.zrx.springboot.entity.User;
import com.zrx.springboot.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * @author
 */
@Controller
public class IndexController {

    @Autowired
    private AdminService adminService;

    /**
     * 登入页
     */
    @GetMapping(value = {"/login","/"})
    public String longinPage() {

        return "login";
    }

    @PostMapping("/login")
    public String main(Admin admin, Model model, HttpSession session) {
        System.out.println("-----------");
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("adminname", admin.getAdminname());
        queryWrapper.and(i ->i.eq("password",admin.getPassword()));
        Admin one = adminService.getOne(queryWrapper);
        System.out.println("-----------");
        System.out.println(one);

        if (one!=null) {
            admin.setId(one.getId());
            session.setAttribute("loginUser", admin);
            session.setAttribute("id", one.getId());

            //重定向
            return "redirect:/index.html";
        } else {
            model.addAttribute("msg", "账号密码错误");
            return "login";
        }


    }

    @GetMapping("/index.html")
    public String mainPage(HttpSession session, Model model) {

        return "index";


    }
    @GetMapping("/index_alt.html")
    public String mainPage2(HttpSession session, Model model) {

        return "index_alt";


    }
    @GetMapping("/registration")
    public String mainPage3(HttpSession session, Model model) {

        return "registration";


    }
    /**
     * 添加管理员
     */
    @RequestMapping("/saveadmin")
    public String saveadmin(Admin admin ){

        adminService.save(admin);

        return "redirect:/login";
    }
    /**
     * 检测用户合法
     */
    @ResponseBody
    @RequestMapping("/checkadmin")
    public  String checkUserName(String adminname){
     return adminService.checkadmin(adminname);

    }
}
